package servlet;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import model.User;
import org.apache.commons.beanutils.BeanUtils;
import service.UserService;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;

@WebServlet(name = "UserRegisterServlet", value = "/UserRegisterServlet")
public class UserRegisterServlet extends HttpServlet {
    private UserService uService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        //告诉浏览器，服务器发送的消息体的数据的编码
        response.setHeader("content-type", "text/html;charset=utf-8");
        User user = new User();
        PrintWriter pw =response.getWriter();

        try {
            BeanUtils.copyProperties(user, request.getParameterMap());
//            System.out.println(user+"========");//测试
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        if (uService.register(user)) {
            pw.print("<script>alert('注册成功，请登录~~~~~!'); window.location='login.jsp' </script>");
        } else {
            pw.print("<script>alert('用户名，电话，邮箱重复，请重新填写~~~~！'); window.location='register.jsp' </script>");
        }
    }
}
